package com.symria.system.servlet;


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;

import com.swetake.util.Qrcode;

public class QRCodeEncode extends HttpServlet {
	private static  String url = "";
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			request.setCharacterEncoding("UTF-8");
			url = "http://"+request.getServerName()+"/index.html?";
			String par = request.getParameter("p");
			//String s = URLEncoder.encode("type=A&ID=123", "gbk");
			//System.out.println(s);
			ImageIO.write(create_image(url+par), "jpg", response.getOutputStream());
		}catch(Exception e){
			//logger.error("exception error:"+e.getMessage());
		}finally{
			response.getOutputStream().close();
		}
	}
	@Override
	public void init() throws ServletException {
		super.init();
	}
	public static BufferedImage create_image(String sms_info)throws Exception{
		BufferedImage bi = new BufferedImage(392, 392, BufferedImage.TYPE_BYTE_BINARY);  
		try{
	            Qrcode qrcode =new Qrcode();
	            qrcode.setQrcodeErrorCorrect('M');
	            qrcode.setQrcodeEncodeMode('B');
	            qrcode.setQrcodeVersion(7);
	            String testString = sms_info;
	            byte[] d = testString.getBytes("gbk");
	            Graphics2D g = bi.createGraphics();
	            g.setBackground(Color.WHITE);
	            g.clearRect(0, 0, 392, 392);
	            g.setColor(Color.BLACK);
	            
	            // 限制最大字节数为120
	            if (d.length>0 && d.length <120){
	                boolean[][] s = qrcode.calQrcode(d);
	                for (int i=0;i<s.length;i++){
	                    for (int j=0;j<s.length;j++){
	                        if (s[j][i]) {
	                            g.fillRect(j*8+16,i*8+16,8,8);
	                        }
	                    }
	                }
	            }
	            g.dispose();
	            bi.flush();  
		        } // end try
		        catch (Exception e) {
		            e.printStackTrace();
		        } // end catch
		        return bi;
		 }


	
}
